import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { apiUserInfo } from '@/api/user.js'
const tokenKey = 'auth-token'

// 异步请求的Thunk action creator
export const fetchUser = createAsyncThunk(
  'user/fetchUser',
  async () => {
    const res = await apiUserInfo();
    return res;
  }
);

export const counterSlice = createSlice({
  name: "user",
  initialState: {
    token: sessionStorage.getItem([tokenKey]) || null,
    infoStatus: null,
    info: null,
    roles: [],
    permissions: []
  },
  reducers: {
    setToken: (state, {payload}) => {
      state.token = payload;
      sessionStorage.setItem([tokenKey],payload);
    },
    removeToken: (state) => {
      state.token = null;
      sessionStorage.setItem([tokenKey], '');
      state.infoStatus = null;
      state.info  = null;
      state.roles  = [];
      state.permissions  = [];
    },
    setInfoStatus: (state,{payload}) => {
      state.infoStatus = payload;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUser.pending, (state) => {
        state.infoStatus = 'loading';
      })
      .addCase(fetchUser.fulfilled, (state, {payload}) => {
        state.infoStatus = 'fulfilled';
        const { user, roles, permissions} = payload;
        state.info  = user;
        state.roles  = roles;
        state.permissions  = permissions;
      })
      .addCase(fetchUser.rejected, (state) => {
        state.infoStatus = null;
        state.info  = null;
        state.roles  = [];
        state.permissions  = [];
      });
  },
});

// 每个 case reducer 函数会生成对应的 Action creators
export const { setToken, removeToken, testD, setInfoStatus } = counterSlice.actions;

export default counterSlice.reducer;
